<template>
  <div class="tp" v-loading="state.loading">
    <Header />
    <Content>
      <div class="cp" style="height: 100%">
        <a-row :gutter="16" style="height: 100%">
          <a-col span="6">
            <a-flex vertical style="height: 100%">
              <div class="vip-head">
                <a-flex align="center" gap="middle" style="position: relative">
                  <a-avatar
                    :size="52"
                    :src="OSS_IMG_URL(recordRef.memberWeixinDataBean?.headImgUrl, vipAvatar)"
                  />
                  <span v-if="recordRef.birthday">
                    <img
                      src="@/assets/img2/cake.png"
                      v-if="
                        (!!recordRef.birthday &&
                          dayjs().month() === dayjs(recordRef.birthday).month()) ||
                        Lunar.fromDate(new Date()).getMonthInChinese() ===
                          Solar.fromDate(dayjs(recordRef.birthday).toDate())
                            .getLunar()
                            ?.toString()
                            .slice(5, 6)
                      "
                      alt=""
                      style="
                        width: 14px;
                        height: 14px;
                        position: absolute;
                        left: 40px;
                        top: 32px;
                        z-index: 10;
                      "
                    />
                  </span>
                  <span v-else> </span>

                  <div>
                    <a-flex gap="small" align="flex-end">
                      <span class="name"> {{ recordRef.realName }}</span>
                      <span class="tag" style="margin-bottom: 2px">
                        {{
                          recordRef.memberType == 1
                            ? '新客'
                            : recordRef.memberType == 2
                              ? '体验客'
                              : recordRef.memberType == 3
                                ? '会员'
                                : recordRef.memberType
                        }}
                      </span>
                    </a-flex>
                    <div class="d-regular mobile">
                      {{ recordRef.mobile?.replace(/(\d{3})(\d{4})(\d{4})/, '$1 $2 $3') }}
                    </div>
                  </div>
                </a-flex>
              </div>
              <div
                v-if="recordRef.debtAmount > 0"
                style="padding: 10px 0; overflow: hidden"
                class="amount_arrears-box"
              >
                <a-row>
                  <a-col class="amount_arrears-col" :span="9" :offset="3">
                    <div>
                      <div class="amount_arrears_backgroundimage">
                        <span>欠款</span>
                      </div>
                    </div>
                    <div class="amount_arrears_content"
                      ><span>￥</span><span>{{ recordRef.debtAmount }}</span></div
                    >
                  </a-col>
                  <a-col class="amount_arrears_button" :span="8" :offset="4">
                    <a-button size="small" @click="onRepayment">还款</a-button>
                  </a-col>
                </a-row>
              </div>
              <div class="vip-card !px-5">
                <a-row>
                  <a-col :span="16">
                    <div v-if="!recordRef.labelList?.length" class="empty !text-[#ccc] !text-left">
                      暂无标签</div
                    >
                    <a-flex v-else gap="small" wrap="wrap">
                      <div
                        class="tag-item"
                        v-for="(label, index) in recordRef.labelList"
                        :key="index"
                        >{{ label }}
                      </div>
                    </a-flex>
                  </a-col>
                  <a-col :span="8" class="text-right">
                    <a-divider type="vertical" class="p-line-bg" />
                    <a @click="onTag" style="margin-left: 4px">+标签</a>
                  </a-col>
                </a-row>

                <a-divider style="margin: 12px 0" />

                <div class="chunk" style="margin-top: 16px">
                  <div class="c-title">基础信息</div>
                  <a-row :gutter="[12, 12]">
                    <a-col :span="8" class="f-label"> 进店渠道</a-col>
                    <a-col :span="16" class="f-value">
                      {{ getLabel(memberSources, recordRef.memberSource) || '--' }}
                    </a-col>
                    <a-col :span="8" class="f-label"> 阳历生日</a-col>
                    <a-col :span="16" class="f-value">
                      {{ recordRef.birthday || '--' }}
                    </a-col>
                    <a-col :span="8" class="f-label"> 农历生日</a-col>
                    <a-col :span="16" class="f-value">
                      {{ solar2Lunar(recordRef.birthday) || '--' }}
                    </a-col>
                    <a-col :span="8" class="f-label"> 婚姻状况</a-col>
                    <a-col :span="16" class="f-value">
                      {{ getLabel(marrys, recordRef.marry) || '--' }}
                    </a-col>
                    <a-col :span="8" class="f-label"> 职业</a-col>
                    <a-col :span="16" class="f-value">
                      {{ recordRef.job || '--' }}
                    </a-col>
                    <a-col :span="8" class="f-label"> 家庭住址</a-col>
                    <a-col :span="16" class="f-value">
                      {{ recordRef.homeAddress || '--' }}
                    </a-col>
                  </a-row>
                </div>

                <div class="chunk" style="margin-top: 24px">
                  <div class="c-title">补充信息</div>
                  <a-row :gutter="[12, 12]">
                    <a-col :span="8" class="f-label"> 皮肤情况</a-col>
                    <a-col :span="16" class="f-value">
                      {{ recordRef.allergy?.split(',')?.join('、') || '--' }}
                    </a-col>
                    <a-col :span="8" class="f-label"> 护肤习惯</a-col>
                    <a-col :span="16" class="f-value">
                      {{ recordRef.skincareHabits?.split(',')?.join('、') || '--' }}
                    </a-col>
                    <a-col :span="8" class="f-label"> 护肤诉求</a-col>
                    <a-col :span="16" class="f-value">
                      {{ recordRef.skincareNeeds?.split(',')?.join('、') || '--' }}
                    </a-col>
                    <a-col :span="8" class="f-label"> 过往美容史</a-col>
                    <a-col :span="16" class="f-value">
                      {{ recordRef.pastBeautyHistory?.split(',')?.join('、') || '--' }}
                    </a-col>
                    <a-col :span="8" class="f-label"> 补充说明</a-col>
                    <a-col :span="16" class="f-value">
                      {{ recordRef.additionalRemarks || '--' }}
                    </a-col>
                  </a-row>
                </div>
                <a-divider />

                <a-button type="primary" @click="onEdit">编辑客户</a-button>
              </div>
            </a-flex>
          </a-col>
          <a-col span="18">
            <div class="card" style="height: 100%">
              <a-flex vertical style="height: 100%">
                <a-flex gap="large" class="tab-list">
                  <div
                    v-for="(item, index) in state.tabList"
                    :key="index"
                    :class="['use tab', state.tabIndex === index ? 'active' : 'tacit']"
                    @click="state.tabIndex = index"
                  >
                    {{ item.label }}
                  </div>
                </a-flex>

                <div class="t-body" v-if="!!recordRef.memberCode">
                  <component
                    :is="state.tabList[state.tabIndex]?.component"
                    :memberCode="recordRef.memberCode"
                  />
                </div>
                <div class="start-cashier" v-if="state.tabIndex == 0">
                  <a-button type="primary" @click="startCashier">开单收银</a-button>
                </div>
              </a-flex>
            </div>
          </a-col>
        </a-row>
      </div>
    </Content>

    <Edit @register="registerEdit" @complete="loadDetail" />
    <Tag @register="registerTag" @complete="loadDetail" />
    <Repayment
      @register="registerRepayment"
      :memberInfo="recordRef"
      @complete="onRepamentComplete"
    />
    <DebtLogDetail @register="registerDebtLog" />
  </div>
</template>

<script setup>
  import { defineOptions, onMounted, provide, reactive, ref } from 'vue';

  import Header from '@/widget/header.vue';
  import Content from '@/widget/content.vue';
  import { GET, DELETE, PAGE, POST } from '@/api/http';
  import { getLabel, marrys, memberSources, OSS_IMG_URL } from '@/api/ds';
  import { useMessage } from '@/hooks/web/useMessage';
  import { useRoute, useRouter } from 'vue-router';

  import Edit from './edit.vue';
  import Tag from './tag.vue';
  import Repayment from './repayment.vue';
  import { useDrawer } from '@/components/Drawer';

  import vipAvatar from '@/assets/images/vip-avatar.png';

  import NoteLog from './note-log.vue';
  import TransactionLog from './transaction-log.vue';
  import ServiceLog from './service-log.vue';
  import DepositLog from './deposit-log.vue';
  import CardLog from './card-log.vue';
  import { solar2Lunar } from '@/api/util.js';
  import dayjs from 'dayjs';
  import { Solar, Lunar } from 'lunar-javascript';
  import { savePendingOrder } from '../cashier/cart';
  import DebtLogDetail from '@/views/member/debt-log-detail.vue';

  defineOptions({ name: 'MemberDetail' });

  const [registerEdit, { openDrawer: editDrawer }] = useDrawer();
  const [registerTag, { openDrawer: tagDrawer }] = useDrawer();
  const [registerRepayment, { openDrawer: repaymentDrawer }] = useDrawer();
  const [registerDebtLog, { openDrawer: debtLogDrawer }] = useDrawer();

  provide('onSearch', { onSearch: () => {} });

  const route = useRoute(),
    router = useRouter();

  const { createMessage, createConfirm } = useMessage();

  const { memberCode = null } = route.query;

  const state = reactive({
    loading: false,
    tabIndex: 0,
    tabList: [
      {
        label: '客户权益',
        component: CardLog,
      },
      {
        label: '交易记录',
        component: TransactionLog,
      },
      {
        label: '服务记录',
        component: ServiceLog,
      },
      {
        label: '服务日志',
        component: NoteLog,
      },
      {
        label: '物品寄存',
        component: DepositLog,
      },
    ],
  });

  const recordRef = ref({});

  onMounted(() => {
    loadDetail();
  });

  provide('onSavePendingOrder', { onSavePendingOrder });

  async function onSavePendingOrder() {
    const { takeId, workDate } = state;
    await savePendingOrder({ memberInfo: recordRef.value, takeId, workDate });

    createMessage.success('已挂单');
    router.replace('/cashier/index/take-order');
  }

  async function loadDetail() {
    const result = (await GET('/membership/getMemberBaseInfo', { memberCode })) ?? {};
    result.labelList ||= [];

    recordRef.value = result;
  }

  function onEdit() {
    const { memberCode } = recordRef.value;
    editDrawer(true, { behavior: 'edit', memberCode });
  }
  // 用户还款窗口
  function onRepayment() {
    repaymentDrawer(true, { behavior: 'edit', memberCode });
  }

  function onTag() {
    const { memberCode, labelList } = recordRef.value;
    tagDrawer(true, { memberCode, labelList });
  }

  // 跳转至开单页
  async function startCashier() {
    function toCashier(query = {}) {
      router.push({
        path: '/cashier/index',
        query: { memberCode: recordRef.value.memberCode, ...query },
      });
    }
    const { list } =
      (await PAGE('/cashier/getPendingOrder')({ memberCode, currentPage: 1, pageSize: 999999 })) ??
      {};

    const target = list?.[0];
    if (!target) {
      toCashier();
    } else {
      createConfirm({
        content: '该客户还有未完成的挂单，是否继续开单？',
        okText: '继续开单',
        cancelText: '忽略，重新开单',
        onOk: async () => {
          toCashier({ takeId: target.id });
        },
        onCancel: async () => {
          await DELETE('/cashier/delPendingOrder', { memberCode, id: target.id });
          toCashier();
        },
      });
    }
  }

  async function onRepamentComplete() {
    loadDetail();
    const { list } = await POST('/membership/debtsList', {
      currentPage: 1,
      pageSize: 9999,
      query: recordRef.value.realName,
      repaymentStatus: 0,
    });

    const record = list.find((d) => d.memberCode === recordRef.value.memberCode);

    if (record) {
      debtLogDrawer(true, { record });
    }
  }
</script>
<style lang="less" scoped>
  .card {
    padding: 12px;

    .tab-list {
      position: relative;
      padding-bottom: 12px;
      border-bottom: 1px solid #d8d8d8;
      cursor: pointer;

      .tab {
        flex: 1;
        text-align: center;
        position: relative;
        border-bottom: 1px solid #d8d8d8;
        left: 0;
        right: 0;
        padding-bottom: 12px;
        bottom: -13px;
        z-index: 1;
        color: #666666;
      }
      .active {
        color: #f2a8ba;
        border-bottom: 2px solid #f2a8ba;
      }
    }

    .t-body {
      flex: 1;
    }

    .start-cashier {
      display: flex;
      justify-content: flex-end;
    }
  }

  .vip-head {
    background-image: url('@/assets/images/vip-head-bg.png');
    background-repeat: no-repeat;
    background-position: center top;
    background-size: cover;

    padding: 12px 12px 8px 16px;

    .name {
      font-weight: 500;
      font-size: 18px;
      color: #ce7b90;
    }

    .tag {
      background: linear-gradient(90deg, #f79dbb 0%, #eb6485 100%);
      border-radius: 32px;
      font-size: 11px;
      color: #ffffff;
      padding: 2px 6px;
    }

    .mobile {
      font-weight: 400;
      font-size: 14px;
      color: #ce7b90;
      margin-top: 6px;
    }
  }

  .amount_arrears-box {
    border-top-left-radius: 10px;
    border-top-right-radius: 10px;
    background: linear-gradient(to bottom, #ffffff, #fff6f8);
    margin-bottom: -10px;
    line-height: 50px;

    .amount_arrears-col {
      margin-left: 10px;
      display: flex;
      // line-height: 50px;
    }

    .amount_arrears_button {
      button {
        margin-left: 35px;
        width: 60px;
        border: 1px #f1a3b8 solid;
        color: #f1a3b8;
      }
    }

    .amount_arrears_backgroundimage {
      color: #eb6485;
      font-size: 12px;
      font-weight: 500;
      width: 50px;
      height: 50px;
      background-image: url('@/assets/images/amount_arrears.png');
      background-repeat: no-repeat;
      background-position: center top;
      background-size: cover;

      span {
        display: flex;
        justify-content: center;
        // line-height: 50px;
      }
    }

    .amount_arrears_content {
      color: #af3452;
      line-height: 50px;

      span:nth-child(1) {
        font-size: 12px;
      }
      span:nth-child(2) {
        font-size: 16px;
        font-weight: 500;
      }
    }
  }

  .vip-card {
    background: #ffffff;
    // box-shadow: 0px -3px 6px 0px rgba(229, 201, 182, 0.51);
    border-radius: 8px;
    padding: 18px 24px;
    flex: 1;
  }

  .chunk {
    .c-title {
      font-weight: 500;
      font-size: 15px;
      color: #333333;
      margin-bottom: 12px;
    }
  }

  .tag-item {
    font-weight: 400;
    font-size: 14px;
    color: #eb6485;
    background: #fff1f4;
    border-radius: 4px;
    border: 1px solid #ffdfe7;
    padding: 2px 6px;
  }
</style>
